package com.siruier.boss.ui.activity.login

import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import android.widget.CompoundButton
import com.didi.drouter.annotation.Router
import com.siruier.boss.App
import com.siruier.boss.BuildConfig
import com.siruier.boss.R
import com.siruier.boss.api.core.MD5Util
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.loginApi
import com.siruier.boss.bean.DeviceInfoBean
import com.siruier.boss.common.AGREEMENT
import com.siruier.boss.common.PRIVACY_POLICY
import com.siruier.boss.databinding.ActivityLoginBinding
import com.siruier.boss.router.ROUTER_HOST
import com.siruier.boss.router.ROUTER_PATH_LOGIN
import com.siruier.boss.router.ROUTER_SCHEME
import com.siruier.boss.ui.activity.commom.openUrl
import com.siruier.boss.ui.activity.main.MainActivity
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.cache.UserCache
import com.siruier.boss.ui.ext.*
import com.siruier.boss.ui.helper.DeviceInfoHelper
import com.siruier.boss.ui.helper.localSendBroadcast
import com.siruier.boss.ui.listener.UMAuthListener
import com.siruier.boss.ui.utils.*
import com.siruier.boss.ui.widget.ContactTextView
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA

@Router(scheme = ROUTER_SCHEME, host = ROUTER_HOST, path = ROUTER_PATH_LOGIN)
class LoginActivity : BaseActivity<ActivityLoginBinding>() {

    override fun initView() {
        bindViewClick(vb.tvForgetPassword, vb.bottomLogin, vb.ivWxLogin)
        vb.titleView.rightTextView.textSize = 16.toFloat()
        vb.titleView.isShowLeft = false
        vb.titleView.onRightTextClickListener = {
            launchStartActivityForResult(RegisterActivity::class.java) {
                it.data?.let {
                    vb.etPhone.setText(it.getStringExtra("phone"))
                    vb.etPasswrod.setText(it.getStringExtra("passwrod"))
                    vb.bottomLogin.performClick()
                }
            }
        }
        variableView {
            addTextView(vb.etPhone)
            addTextView(vb.etPasswrod)
            addOnValidationResultListener(vb.bottomLogin)
            addOnValidationInterceptListener(this@LoginActivity::validator)
        }
    }

    override fun initData() {
        vb.etPhone.setText(SPUtils.getString("key_phone"))
        val password = SPUtils.getString("key_password")
        vb.cbRememberPassword.isChecked = password.isNotBlank()
        vb.etPasswrod.setText(password)
        ActivityManger.finishAllActivity(LoginActivity::class.java)
        initServiceClause()
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.tvForgetPassword -> startActivityExt<ForgetPasswordActivity>()
            vb.bottomLogin -> {
                Utils.hideSoftInput(this)
                if (!vb.cbServiceClause.isChecked) {
                    "请先同意隐私政策和用户协议".toastMessageLong()
                    return
                }
                SPUtils.put("service_clause", vb.cbServiceClause.isChecked)
                launchUI({
                    val mDeviceInfoBean: DeviceInfoBean = DeviceInfoHelper.getDeviceInfoBean()
                    val mAccessTokenBean = loginApi.phoneLogin(
                        vb.etPhone.value,
                        MD5Util.md5(vb.etPasswrod.value),
                        App.OAID,
                        mDeviceInfoBean.isRoot.toInt,
                        mDeviceInfoBean.isBeingTraced.toInt,
                        mDeviceInfoBean.isXposed.toInt,
                        mDeviceInfoBean.isVirtual.toInt,
                        mDeviceInfoBean.isEmulator.toInt,
                        mDeviceInfoBean.isVpn.toInt,
                    ).toData()
                    SPUtils.put("key_phone", vb.etPhone.value)
                    if (vb.cbRememberPassword.isChecked) {
                        SPUtils.put("key_password", vb.etPasswrod.value)
                    }
                    if (mAccessTokenBean != null) {
                        UserCache.saveToken(mAccessTokenBean.accessToken)
                    }
                    UserCache.saveUserInfoBean(loginApi.userInfo().toData())
                }, ApiObserver(this) {
                    goMain()
                    localSendBroadcast(ACTION_USER_LOGIN)
                })
            }
            vb.ivWxLogin -> {
                UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, UMAuthListener(onComplete = { platform, param ->
                    Logger.e("param==>${param}")
//                    mLoginViewModel.thirdPartLogin(param["openid"] ?: "", param["unionid"] ?: "", ApiObserver {
//                        it?.let {
//                            if (it.isRegisted) {
//                                mUserViewModel.loadUserData(it.token ?: "", ApiObserver(this, commonButton = buttonLogin) {
//                                    UserDataCache.login(intent.extras, this)
//                                })
//                            } else {// 跳转绑定微信
//                                goActicity(PhoneCheckActivity::class.java, bundle = Bundle().apply {
//                                    putBoolean(PhoneCheckActivity.FOR_WX_BIND, true)
//                                    putString(PhoneCheckActivity.THIRD_PART_ID, param.get("openid"))
//                                    putString(PhoneCheckActivity.UNION_ID, param.get("unionid"))
//                                    intent?.extras?.let { putAll(it) }
//                                })
//                            }
//                        }
//                    })
                }))
            }
        }
    }

    private fun goMain() {
        startActivityExt<MainActivity>()
        finish()
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
    }

    private fun validator(view: View) = when (view) {
        vb.etPhone -> vb.etPhone.length() == 11
        else -> null
    }

    private fun initServiceClause() {
        vb.tvServiceClause.movementMethod = ContactTextView.LocalLinkMovementMethod.getInstance();
        vb.tvServiceClause.textSpan("阅读并同意《隐私政策》《用户协议》") {
            spanText = "《隐私政策》"
            addForegroundColorSpan(R.color.main_color.toColor())
            addClickableSpan(object : ClickableSpan() {
                override fun onClick(view: View) {
                    openUrl(PRIVACY_POLICY)
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.isUnderlineText = false
                }
            })
            spanText = "《用户协议》"
            addForegroundColorSpan(R.color.main_color.toColor())
            addClickableSpan(object : ClickableSpan() {
                override fun onClick(view: View) {
                    openUrl(AGREEMENT)
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.isUnderlineText = false
                }
            })
        }
        vb.cbServiceClause.isChecked = SPUtils.getBoolean("service_clause", false)
    }
}